<template>
  <div class="roles">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card -->
    <el-card>
      <el-button type="primary" @click="dialogVisible = !dialogVisible"
        >添加角色</el-button
      >
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scoped">
            <!-- 一级权限 -->
            <el-row
              v-for="(item1, i1) in scoped.row.children"
              :key="item1.id"
              :style="{
                'border-bottom': '1px solid #eee',
                'border-top': i1 == 0 ? '1px solid #eee' : ''
              }"
            >
              <el-col :span="5">
                <el-tag @close="removeRight(scoped.row, item1.id)" closable>{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :style="{ 'border-top': i2 == 0 ? '' : '1px solid #eee' }"
                >
                  <el-col :span="5">
                    <el-tag
                      @close="removeRight(scoped.row, item2.id)"
                      type="success"
                      closable
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="19">
                    <!-- 三级权限 -->
                    <el-tag
                      @close="removeRight(scoped.row, item3.id)"
                      type="warning"
                      closable
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scoped">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="getRoleById(scoped.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delRoleList(scoped.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRight(scoped.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色弹框 -->
    <el-dialog
      title="添加角色"
      @close="resetForm"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-form :model="addForm" :rules="addrules" ref="addruleForm">
        <el-form-item label="角色名称" prop="roleName" label-width="80px">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc" label-width="80px">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleList">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色弹框 -->
    <el-dialog title="编辑角色" :visible.sync="editDialog" width="50%">
      <el-form :model="editForm" :rules="editrules" ref="editruleForm">
        <el-form-item label="角色名称" prop="roleName" label-width="80px">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc" label-width="80px">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="editRoleList">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightdialog" width="50%">
      <!-- 渲染权限的树形结构 -->
      <el-tree
        :data="rightTree"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defaultCheckedKeys"
        ref="rightsRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightdialog = false">取 消</el-button>
        <el-button type="primary" @click="assignRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表数据
      rolesList: [],
      // 添加角色弹框
      dialogVisible: false,
      // 添加角色字段
      addForm: {
        roleName: "",
        roleDesc: ""
      },
      // 添加角色校验规则
      addrules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 3, max: 50, message: "长度在 3 到 50 个字符", trigger: "blur" }
        ]
      },
      // 编辑角色弹框
      editDialog: false,
      // 编辑角色字段
      editForm: {
        roleName: "",
        roleDesc: ""
      },
      // 编辑角色校验规则
      editrules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 3, max: 50, message: "长度在 3 到 50 个字符", trigger: "blur" }
        ]
      },
      // 分配权限弹框
      setRightdialog: false,
      // 权限树形结构对应的数据
      rightTree: [],
      // 树形结构中，每个节点和数据的对应关系
      treeProps: {
        // 指定要展示的节点内容
        label: "authName",
        // 指定嵌套关系
        children: "children"
      },
      // 默认情况下 角色已经拥有的三级权限数组
      defaultCheckedKeys: [],
      // 即将要被分配权限的id
      roleId: ""
    };
  },
  methods: {
    // 获取角色列表数据
    async getrolesList() {
      // 发起ajax请求
      let { data: res } = await this.$http.get("roles");
      //   console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败");
      // 把数据给rolesList
      this.rolesList = res.data;
    },
    // 添加角色
    addRoleList() {
      // 表单校验是否通过
      this.$refs.addruleForm.validate(async valid => {
        // 如果校验失败 return
        if (!valid) return false;
        // 发起Ajax请求
        let { data: res } = await this.$http.post("roles", this.addForm);
        // console.log(res);
        if (res.meta.status !== 201) return this.$message.error("角色添加失败");
        // 刷新页面
        this.getrolesList();
        // 弹框关闭
        this.dialogVisible = false;
        // 角色添加成功
        this.$message.success("角色添加成功");
      });
    },
    // 清空表单
    resetForm() {
      this.$refs.addruleForm.resetFields();
    },
    // 编辑 根据id获取角色
    async getRoleById(id) {
      // 点击编辑按钮 让弹框打开
      this.editDialog = true;
      // 发起ajax请求
      let { data: res } = await this.$http.get(`roles/${id}`);
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error("获取角色失败");
      // 把获取到的数据给editForm
      this.editForm = res.data;
    },
    // 编辑角色
    editRoleList() {
      // 看看是否通过了校验
      this.$refs.editruleForm.validate(async valid => {
        // 如果没有 return
        if (!valid) return false;
        // 发起ajax请求
        let { data: res } = await this.$http.put(
          `roles/${this.editForm.roleId}`,
          this.editForm
        );
        // console.log(res);
        if (res.meta.status !== 200) return this.$message.error("角色编辑失败");
        // 刷新页面
        this.getrolesList();
        // 弹框关闭
        this.editDialog = false;
        // 编辑成功
        this.$message.success("角色编辑成功");
      });
    },
    // 删除角色
    async delRoleList(id) {
      let result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(error => {
        return error;
      });
      // 判断如果结果等于confirm
      if (result == "confirm") {
        // 发起ajax请求
        let { data: res } = await this.$http.delete(`roles/${id}`);
        // 如果状态值不等于200 删除失败
        if (res.meta.status !== 200) return this.$message.error("用户删除失败");
        // 否则成功 刷新页面
        this.getrolesList();
        this.$message.success("用户删除成功");
        // 如果结果等于cancel 就取消删除
      } else if (result == "cancel") {
        this.$message({
          type: "info",
          message: "已取消删除!"
        });
      }
    },
    // 根据权限id删除指定角色下的权限
    async removeRight(role, rightId) {
      // console.log(role);
      // console.log(rightId);
      // 询问用户是否要删除权限
      const result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(error => {
        error;
      });
      // 用户不想删除
      if (result !== "confirm") {
        return this.$message({
          type: "info",
          message: "已取消删除"
        });
      }
      // 发起ajax请求
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status !== 200) return this.$message.error("删除权限失败");
      // 删除成功
      this.$message.success("删除权限成功");
      // 刷新 把服务器返回的最新的权限数组赋值给当前角色的children属性
      role.children = res.data;
    },
    // 点击按钮展示分配权限的对话框
    async showSetRight(role) {
      // 预先把角色id存储到data上的roleId属性中
      this.roleId = role.id;
      // 弹框打开
      this.setRightdialog = true;
      // 发起ajax请求
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) return this.$message.error("获取权限失败");
      // 把拿到的数据给树形结构展示
      this.rightTree = res.data;
      // 吊用递归，获取指定角色下所有三级权限的id
      // 空数组用来存储三级权限id
      const keys = [];
      this.getLeafId(role, keys);
      // console.log(keys);
      this.defaultCheckedKeys = keys;
    },
    // 递归获取角色下所有三级权限id
    getLeafId(node, keyArr) {
      // 如果这个节点没有children属性 就直接把这个叶子节点存起来
      if (!node.children) {
        return keyArr.push(node.id);
      }
      // 如果有children属性 就循环
      node.children.forEach(item => this.getLeafId(item, keyArr));
    },
    // 点击确定分配权限
    async assignRight() {
      // 获取全选的key数组
      const k1 = this.$refs.rightsRef.getCheckedKeys();
      // 获取半选的key数组
      const k2 = this.$refs.rightsRef.getHalfCheckedKeys();
      // 拼接出所有被勾选的权限的id
      const idStr = [...k1, ...k2].join(",");
      // 发起ajax请求
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: idStr
        }
      );
      if (res.meta.status !== 200) return this.$message.error("分配权限失败");
      this.$message.success("分配权限成功");
      // 刷新页面
      this.getrolesList();
      // 弹框关闭
      this.setRightdialog = false;
    }
  },
  created() {
    this.getrolesList();
  }
};
</script>

<style lang="less" scoped>
.el-card,
.el-table {
  margin-top: 15px;
}

.el-tag {
  margin: 10px 5px;
}
</style>
